package com.alibaba.dubbo.remoting.msgcodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream;
import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream;
import com.alibaba.dubbo.remoting.MessageEncode;
import com.alibaba.dubbo.remoting.MessageEncodeRegistry;

public class EncodeWrapper implements MessageEncode {
	
	private MessageEncode[] encoder;
	public EncodeWrapper(MessageEncode []encoder){
		this(encoder, false);
	}
	
	public EncodeWrapper(MessageEncode []encoder, boolean reverse){
		if(reverse){
			this.encoder = new MessageEncode[encoder.length];
			for(int  i = 0;i<encoder.length;i++){
				this.encoder[i] = encoder[encoder.length - 1 -i];
			}
		}else{
			this.encoder = new MessageEncode[encoder.length];
			for(int  i = 0;i<encoder.length;i++){
				this.encoder[i] = encoder[i];
			}
		}
	}

	@Override
	public int encode(InputStream in, OutputStream out/*, MessageEncodeRegistry registry*/) throws IOException {
		InputStream a = in;
		if(encoder.length > 1){
			UnsafeByteArrayOutputStream b = new UnsafeByteArrayOutputStream(4096);
			for(int i = 0;i < encoder.length-1;i++){
				int l = encoder[i].encode(a, b/*, registry*/);
				if(l > 0){
					a = new UnsafeByteArrayInputStream(b.detach());
					b.reset();
				}
			}
		}
		return encoder[encoder.length -1].encode(a, out/*, registry*/);
	}

}
